package _4策略模式.加密_解密文件;

import java.io.*;

// 策略 1
public class StrategyOne implements Strategy {
	private final String password;

	public StrategyOne(String password) {this.password = password;}

	@Override
	public void encryptFile(File file) {
		try{
			byte[] a = password.getBytes();
			FileInputStream in = new FileInputStream(file);
			long length = file.length();
			byte[] c = new byte[(int) length];
			int m = in.read(c);
			for (int i = 0; i < m; i++) {
				int n = c[i]+a[i%a.length];     // 加密算法
				c[i] = (byte) n;
			}
			in.close();

			FileOutputStream out = new FileOutputStream(file);
			out.write(c,0,m);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String decryptFile(File file) {
		try {
			byte[] a = password.getBytes();
			long length = file.length();
			FileInputStream in = new FileInputStream(file);
			byte[] c= new byte[(int) length];
			int m = in.read(c);
			for (int i = 0; i <m; i++) {
				int n = c[i] - a[i%a.length];   //解密算法
				c[i] = (byte) n;
			}
			in.close();
			return new String(c,0,m);
		} catch (IOException e) {
			return e.toString();
		}
	}
}



